package net.easyjava.third.letv.util;

import com.alibaba.fastjson.JSONObject;
import net.easyjava.third.letv.bean.LetvResult;
import net.easyjava.tools.http.HttpTools;
import net.easyjava.tools.security.md5.Md5Tools;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.Collator;
import java.util.*;

public class LetvApiUtil {
    private static Logger logger = LoggerFactory.getLogger(LetvApiUtil.class);

    /**
     * 获取接口返回公共参数
     * @param url
     * @param heads
     * @param parameter
     * @return
     * @throws IOException
     */
    public static LetvResult getResult(String url,Map<String,String> heads,Map<String,String> parameter) throws IOException {
        String rtn = HttpTools.post(url, heads, parameter);
        LetvResult result = JSONObject.parseObject(rtn, LetvResult.class);
        System.out.println(String.format("letv 接口返回结果 code[%s] message[%s]",result.getCode(),result.getMessage()));
        logger.info("letv 接口返回结果 code[{}] message[{}]",result.getCode(),result.getMessage());
        return result;
    }

    @Deprecated
    public static String digest(Map<String, String> params, String secret) {
        StringBuilder result = new StringBuilder();
        List<String> keys = new ArrayList<String>(params.keySet());// map中的参数是区分大小写的
        Collections.sort(keys);
        for (Iterator<String> iterator = keys.iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            if (!"sign".equalsIgnoreCase(key)) { // 必须这么写，set里调用remove方法，无法忽略大小写;request里的map无法remove
                result.append(key).append(params.get(key));
            }
        }
        result.append(secret);
        return Md5Tools.md5(result.toString());
    }


    /**
     * generate MD5
     *
     * @param src
     * @return
     * @throws Exception
     */
    @Deprecated
    public static String MD5(String src) {
        try {
            if (src == null) {
                return "";
            }
            byte[] result = null;
            MessageDigest alg = MessageDigest.getInstance("MD5");
            result = alg.digest(src.getBytes("utf-8"));
            return byte2hex(result);
        } catch (Exception e) {
            throw new RuntimeException();
        }

    }

    /**
     * generate MD5
     *
     * @param src
     * @return
     * @throws Exception
     */
    @Deprecated
    public static String MD5(byte[] src) {
        try {
            if (src == null) {
                return "";
            }
            byte[] result = null;
            MessageDigest alg = MessageDigest.getInstance("MD5");
            result = alg.digest(src);
            return byte2hex(result);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Deprecated
    private static String byte2hex(byte[] b) {
        if (b == null) {
            return "";
        }
        StringBuffer hs = new StringBuffer();
        String stmp = null;
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append("0");
            }
            hs.append(stmp);
        }
        return hs.toString();
    }


    public static String encoder(String str) throws UnsupportedEncodingException {
        return URLEncoder.encode(str, "UTF-8");
    }

    public static String generateSign(Map<String,String> parameter,String secretKey)  {
        Comparator comparator = Collator.getInstance(Locale.getDefault());
        if(parameter.containsKey("sign")){
            parameter.remove("sign");
        }
        String[] keys = new String[parameter.keySet().size()];
        int index = 0;
        for(String key:parameter.keySet()){
            keys[index] = key;
            index++;
        }
        Arrays.sort(keys, comparator);
        String readyTosign = "";
        for(String rk:keys){
            readyTosign+=rk+parameter.get(rk);
        }
        return Md5Tools.md5(readyTosign + secretKey);
    }

    public static String getResponseBody(HttpResponse response) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}
